package util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

/**
 * Formatter for log output
 * @author Sion
 * @see http://stackoverflow.com/questions/194765/how-do-i-get-java-logging-output-to-appear-on-a-single-line
 */
public class LogFormatter extends Formatter {

    private static final int LEVEL_LENGTH = 8;
    private static final int CLASS_LENGTH = 50;

	@Override
    public String format(LogRecord record) {
        StringBuilder sb = new StringBuilder();
        //TODO change string format of date
        sb.append(new Date(record.getMillis()))
            .append(" [")
            .append(StringUtil.padRight(record.getLevel().getName() + "]", LEVEL_LENGTH, StringUtil.WHITESPACE_CHAR))
            .append(StringUtil.padRight(record.getSourceClassName() + ":" + record.getSourceMethodName(), CLASS_LENGTH, StringUtil.WHITESPACE_CHAR))
            .append(": ")
            .append(formatMessage(record))
            .append(StringUtil.NEW_LINE);
        if (record.getThrown() != null) {
            try {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                record.getThrown().printStackTrace(pw);
                pw.close();
                sb.append(sw.toString());
            } catch (Exception e) {
            	System.out.println("Error loading formatter: " + e);
            }
        }
        return sb.toString();
    }
}